package proxy;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * Created by zhoujiawei on 2020-09-14.
 */
public class CglibProxy {

    public static void main(String[] args) {
        CalculatorImpl calculator = (CalculatorImpl) getProxy();
        System.out.println(calculator.add(1, 2));
    }


    public static Object getProxy() {
        Object o = Enhancer.create(CalculatorImpl.class, new MethodInterceptor() {
            @Override
            public Object intercept(Object o, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
                System.out.println(method.getName() + " method to start");
                Object invoke = methodProxy.invokeSuper(o, args);
                System.out.println(method.getName() + " method to end");
                return invoke;

            }
        });
        return o;
    }


    /**
     * Created by zhoum on 2019-06-27.
     */
    public static class CalculatorImpl {

        public int add(int a, int b) {
            return a + b;
        }

        public int subtract(int a, int b) {
            return a - b;
        }

        public int divide(int a, int b) {
            return a / b;
        }

        public int multiply(int a, int b) {
            return a * b;
        }
    }
}
